import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Radio } from 'antd-mobile';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons';
import styles from './index.module.less';
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { getEmailCode, getRegister, checkEmail } = $globalServicer('login')
import { useSearchParams } from 'react-router-dom'

const RegisterForm = () => {
  const [form] = Form.useForm();
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [confirmPasswordVisible, setConfirmPasswordVisible] = useState(false);
  const [emailText, setEmailText] = useState('发送验证码');
  const [countdown, setCountdown] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [params] = useSearchParams();
  const invite_code = params.get('invite_code')
  console.log("🚀 ~ RegisterForm ~ invite_code:", invite_code)

  const customNavigate = $globalNavigate()

  const [submitting, setSubmitting] = useState(false);

  const onFinish = async (values) => {
    console.log('🚀 注册表单提交:', values);
    if (submitting) {
      console.log('⚠️ 正在提交中，忽略重复提交');
      return;
    }

    try {
      setSubmitting(true);
      console.log('✅ 开始注册流程');

      if (values.password !== values.password_confirmation) {
        showErrorToast('两次输入的密码不一致');
        setSubmitting(false);
        return;
      }

      const isChecked = await checkEmail(values.email);
      if (isChecked?.exist) {
        showErrorToast('邮箱已被注册');
        setSubmitting(false);
        return;
      }

      const data = {
        ...values,
      };

      await getRegister(data);

      showSuccessToast('注册成功');

      customNavigate('/login');

    } catch (error) {
      showErrorToast(error.message || '注册失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };
  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
    } else if (countdown === 0) {
      setEmailText('发送验证码');
    }
    return () => clearTimeout(timer);
  }, [countdown]);
  useEffect(() => {
    if (invite_code) {
      form.setFieldsValue({ inviter_id: invite_code });
    }
  }, [])
  const sendVerificationCode = async () => {
    const email = form.getFieldValue('email');
    const name = form.getFieldValue('name');
    if (!email) {
      showErrorToast('请先输入邮箱地址');
      return;
    }
    const isChecked = await checkEmail(email)
    if (isChecked?.exist) {
      showErrorToast('邮箱已被注册');
      return
    }
    if (!name) {
      showErrorToast('请先输入用户昵称');
      return;
    }
    setIsLoading(true);
    setEmailText('发送中...');
    const data = {
      email,
      name
    }
    try {
      // 调用后端 API
      await getEmailCode(data);
      showSuccessToast('验证码已发送，如未收到请检查垃圾邮件箱');
      setCountdown(60);
    } catch (error) {
      showErrorToast('发送失败，请稍后重试');
      setEmailText('发送验证码');
    } finally {
      setIsLoading(false);
    }
  };
  const validatePassword = (_, value) => {
    if (!value) {
      return Promise.reject(new Error('请输入密码'));
    }
    if (value.length < 8) {
      return Promise.reject(new Error('密码长度不能少于8个字符'));
    }
    // if (!/[A-Z]/.test(value)) {
    //   return Promise.reject(new Error('密码必须包含至少一个大写字母'));
    // }
    // if (!/[a-z]/.test(value)) {
    //   return Promise.reject(new Error('密码必须包含至少一个小写字母'));
    // }
    // if (!/\d/.test(value)) {
    //   return Promise.reject(new Error('密码必须包含至少一个数字'));
    // }
    // if (!/[!@#$%^&*(),.?":{}|<>]/.test(value)) {
    //   return Promise.reject(new Error('密码必须包含至少一个特殊字符'));
    // }
    return Promise.resolve();
  };
  return (
      <div className={styles.register_page}>
        <div className={styles.container}>
          {/* 头部导航 */}
          <div className={styles.header}>
            <button className={styles.backButton} onClick={() => customNavigate('/login')}>
              <i className="material-icons">arrow_back_ios</i>
            </button>
            <h1 className={styles.title}>注册</h1>
          </div>

          {/* 主要内容区域 */}
          <div className={styles.mainContent}>
            <Form
                form={form}
                onFinish={onFinish}
                requiredMarkStyle='text-required'
            >
              {/* 昵称 */}
              <div className={styles.inputGroup}>
                <label className={styles.inputLabel} htmlFor="name">昵称</label>
                <Form.Item
                    name="name"
                    maxlength='40'
                    rules={[{ required: true, message: '请输入昵称' }]}
                    noStyle
                >
                  <Input placeholder="请输入昵称" className={styles.emailInput} />
                </Form.Item>
              </div>


              {/* 密码 */}
              <div className={styles.inputGroup}>
                <label className={styles.inputLabel} htmlFor="password">密码</label>
                <Form.Item name="password" rules={[{ required: true, validator: validatePassword }]} noStyle>
                  <Input
                      placeholder="请输入密码"
                      type={passwordVisible ? 'text' : 'password'}
                      className={styles.passwordInput}
                  />
                </Form.Item>
              </div>

              {/* 确认密码 */}
              <div className={styles.inputGroup}>
                <label className={styles.inputLabel} htmlFor="confirm-password">确认密码</label>
                <Form.Item name="password_confirmation" rules={[{ validator: validatePassword }]} noStyle>
                  <Input
                      placeholder="请再次输入密码"
                      type={confirmPasswordVisible ? 'text' : 'password'}
                      className={styles.confirmPasswordInput}
                  />
                </Form.Item>
              </div>

              {/* 邮箱 */}
              <div className={styles.inputGroup}>
                <label className={styles.inputLabel} htmlFor="email">邮箱名</label>
                <div className={styles.emailWrapper}>
                  <Form.Item
                      name="email"
                      rules={[
                        { required: true, message: '请输入邮箱' },
                        { type: 'email', message: '请输入有效的邮箱地址' }
                      ]}
                      noStyle
                  >
                    <Input placeholder="请输入邮箱名" className={styles.emailInput} />
                  </Form.Item>
                  <Button
                      size="small"
                      onClick={sendVerificationCode}
                      disabled={isLoading || countdown > 0}
                      className={styles.codeBtn}
                  >
                    {countdown > 0 ? `${countdown}s后重试` : emailText}
                  </Button>
                </div>
              </div>

              {/* 验证码 */}
              <div className={styles.inputGroup}>
                <label className={styles.inputLabel} htmlFor="verification_code">验证码</label>
                <Form.Item
                    name="verification_code"
                    rules={[{ required: true, message: '请输入验证码' }]}
                    noStyle
                >
                  <Input placeholder="请输入验证码" className={styles.emailInput} />
                </Form.Item>
              </div>

              {/* 邀请码 */}
              <div className={styles.inputGroup}>
                <label className={styles.inputLabel} htmlFor="inviter_id">邀请码（选填）</label>
                <div className={styles.inviteCodeWrapper}>
                  <span className={styles.inviteCodePrefix}>WY</span>
                  <Form.Item name="inviter_id" noStyle>
                    <Input
                        placeholder="请输入邀请码"
                        disabled={!!invite_code}
                        className={styles.inviteCodeInput}
                    />
                  </Form.Item>
                </div>
              </div>
            </Form>

            {/* 注册按钮 */}
            <div className={styles.registerButtonGroup}>
              <Button
                  block
                  type="submit"
                  className={styles.registerButton}
                  loading={submitting}
                  disabled={submitting}
                  onClick={() => {
                    console.log('🖱️ 注册按钮被点击');
                    // 手动触发表单验证和提交
                    form.validateFields().then((values) => {
                      console.log('✅ 表单验证通过:', values);
                      onFinish(values);
                    }).catch((errorInfo) => {
                      console.log('❌ 表单验证失败:', errorInfo);
                      // 显示第一个验证错误信息给用户
                      if (errorInfo.errorFields && errorInfo.errorFields.length > 0) {
                        const firstError = errorInfo.errorFields[0];
                        const errorMessage = firstError.errors[0];
                        showErrorToast(errorMessage);
                      } else {
                        showErrorToast('请检查表单填写是否正确');
                      }
                    });
                  }}
              >
                注册
              </Button>
            </div>

            {/* 登录链接 */}
            <div className={styles.loginLink}>
              <p className={styles.loginText}>
                已有账号？ <span className={styles.loginSpan} onClick={() => customNavigate('/login')}>立即登录</span>
              </p>
            </div>
          </div>
        </div>
      </div>
  );
};

export default RegisterForm;